﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
//using FANN.Net;

namespace NodeRecognition
{
    public partial class Form1 : Form
    {
        private MainNodeRecognition main = new MainNodeRecognition();

        public Form1()
        {
            InitializeComponent();

            propertyGrid1.SelectedObject = main;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = saveFileDialog1.FileName;
                var xml = new XmlSerializer(typeof(MainNodeRecognition));
                var stream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
                xml.Serialize(stream, main);
                stream.Close();

            }
        }

        private НастройкиПоискаСимволов setting;

        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
                var xml = new XmlSerializer(typeof(НастройкиПоискаСимволов));
                var stream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                setting = (НастройкиПоискаСимволов)xml.Deserialize(stream);
                stream.Close();
                comboBox1.Text = "";
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(setting.symbolType.Select(t => t.name).ToArray());

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (File.Exists(textBox2.Text))
            {
                Cut(openFileDialog1.FileName, main);
            }
        }

        private List<List<float>> ReadFile(string file)
        {
            var ret = new List<List<float>>();
            string line;
            var stream = new StreamReader(file);
            while ((line = stream.ReadLine()) != null)
            {
                List<float> list = new List<float>();
                try
                {
                    list.AddRange(
                        line.Split(' ')
                            .Where(t => t != "")
                            .Select(s => (float)Convert.ToDouble(s, CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                ret.Add(list);
            }
            stream.Close();
            return ret;
        }

        public void Cut(string file, MainNodeRecognition node)
        {
            var str = ReadFile(file);
            List<List<float[]>> data = new List<List<float[]>>();

            for (var i = 0; i < str[2].Count; i++)
            {
                data.Add(new List<float[]>());
            }
            for (var i = 1; i < str.Count; i = i + 2)
            {
                var input = str[i].Select(t1 => (float)t1).ToArray();

                var d = 0;
                for (var j = 0; j < str[i + 1].Count; j++)
                    if (str[i + 1][j] == 1)
                        d = j;

                data[d].Add(input);


            }
            List<RecognitionNode> nodes = new List<RecognitionNode>();
            nodes.Add(node.Node[0]);
            while (nodes.Count > 0)
            {
                if (nodes[0].FileNet != null && nodes[0].FileNet != "")
                {
                    List<List<int>> value = new List<List<int>>();
                    foreach (var v in nodes[0].Nodes)
                    {
                        List<int> n = new List<int>();
                        List<RecognitionNode> nt = new List<RecognitionNode>();


                        nt.Add(v);
                        while (nt.Count > 0)
                        {
                            if (nt[0].Value>=0)
                            {
                                n.Add(nt[0].Value);
                            }
                            nt.AddRange(nt[0].Nodes);
                            nt.RemoveAt(0);

                        }
                        value.Add(n);
                    }


                    List<List<float[]>> td = new List<List<float[]>>();
                    foreach (var t in value)
                    {
                        List<float[]> l = new List<float[]>();
                        foreach (var tt in t)
                            foreach (var ttt in data[tt])
                                l.Add(ttt);
                        td.Add(l);
                    }
                    Save(td, Path.GetDirectoryName(openFileDialog1.FileName) + "\\" + Path.GetFileNameWithoutExtension(nodes[0].FileNet) + ".dat");
                }

                nodes.AddRange(nodes[0].Nodes);
                nodes.RemoveAt(0);
            }


        }

        public void Save(List<List<float[]>> data, string file)
        {
            List<int[]> p = new List<int[]>();

            for (int index = 0; index < data.Count; index++)
                for (int i = 0; i < data[index].Count; i++)
                    p.Add(new[]{index, i});
            Random r = new Random();
            for (int i = 0; i < p.Count - 1; i++)
            {
                var t = r.Next(i + 1, p.Count);
                var ti = p[i];
                p[i] = p[t];
                p[t] = ti;
              
            }
          

               var fs=     new FileStream(file,
                        FileMode.OpenOrCreate, FileAccess.Write);

            AddText(fs, p.Count + " " + data[0][0].Length + " " + data.Count);
            for (int index = 0; index <Math.Min(1000000, p.Count); index++)
            {
                var v = p[index];
                string s = "";

                foreach (var t in data[v[0]][v[1]])

                    s += t.ToString("G", CultureInfo.InvariantCulture) + " ";
                AddText(fs, s.TrimEnd(' '));
                s = "";
                for (int i = 0; i < data.Count; i++)
                    s += i == v[0] ? "1 " : "0 ";
                AddText(fs, s.TrimEnd(' '));
            }
            fs.Flush();
            fs.Close();

        }

        private static void AddText(FileStream fs, string value)
        {
            var info = new UTF8Encoding(true).GetBytes(value + "\r\n");
            fs.Write(info, 0, info.Length);
            fs.Flush();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox2.Text = openFileDialog1.FileName;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //List<RecognitionNode> nodes = new List<RecognitionNode>();
            //nodes.Add(main.Node[0]);
            //while (nodes.Count > 0)
            //{
            //    if (nodes[0].FileNet != null && File.Exists(Path.GetDirectoryName(textBox1.Text) + "\\" + nodes[0].FileNet))
            //    {
            //        nodes[0].Net = new NeuralNet();
            //        nodes[0].Net.CreateFromFile(Path.GetDirectoryName(textBox1.Text) + "\\" +
            //                                    nodes[0].FileNet);
            //    }

            //    nodes.AddRange(nodes[0].Nodes);
            //    nodes.RemoveAt(0);
            //}


            //var vl = new List<double>();
            //var el = new List<double>();

            //var str = ReadFile(textBox2.Text);
            //var time = new List<double>();

            //for (var i = 1; i < str.Count; i = i + 2)
            //{
            //    var input = str[i].Select(t1 => (double)t1).ToArray();
            //    double ver = 1;
            //    System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();
            //    w.Start();
            //    var o = main.Recognition(input, out ver);
            //    w.Stop();

            //    time.Add(w.ElapsedMilliseconds);
            //    var d = 0;
            //    for (var j = 0; j < str[i + 1].Count; j++)
            //        if (str[i + 1][j] == 1)
            //            d = j;

            //    if (d == o)
            //    {

            //        vl.Add(ver);
            //    }
            //    else
            //    {

            //        el.Add(ver);


            //    }
            //}


            //chart1.Series[0].Color = Color.Green;
            //chart1.Series[1].Color = Color.Red;
            //chart1.Series[0].Points.Clear();
            //chart1.Series[1].Points.Clear();

            //var count = vl.Count + el.Count;
            //for (double i = 0; i <= 1; i += 0.05)
            //{
            //    double vc = 0;
            //    double ec = 0;
            //    foreach (var d in vl)
            //    {
            //        if (d > i) vc++;
            //    }
            //    foreach (var d in el)
            //    {
            //        if (d > i) ec++;
            //    }

            //    chart1.Series[0].Points.AddXY(i, vc / count);
            //    chart1.Series[1].Points.AddXY(i, ec / count);
            //}
            //listBox1.Items.Add("верно=" + vl.Count * 100.0 / count + "%");
            //listBox1.Items.Add("Время=" + time.Average());


        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (setting.symbolType.Count > comboBox1.SelectedIndex && comboBox1.SelectedIndex >= 0)
            {
                propertyGrid1.SelectedObject = setting.symbolType[comboBox1.SelectedIndex];
                main = setting.symbolType[comboBox1.SelectedIndex].NodeRecognition[0];
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
